<template>
  <view class="avatar-container" :style="containerStyle">
    <image 
      class="avatar-image" 
      :src="imgSrc" 
      :style="imgStyle"
      mode="aspectFill"
      @error="handleError"
    />
  </view>
</template>

<script>
import helper from '../utils/helper.js';

export default {
  name: 'AvatarImage',
  props: {
    // 头像资源，可以是MD5值或完整URL
    src: {
      type: String,
      default: ''
    },
    // 头像大小，单位为rpx
    size: {
      type: [Number, String],
      default: 100
    },
    // 形状：circle或square
    shape: {
      type: String,
      default: 'circle'
    },
    // 边框颜色
    borderColor: {
      type: String,
      default: 'transparent'
    },
    // 边框宽度
    borderWidth: {
      type: [Number, String],
      default: 0
    },
    // 默认头像
    defaultSrc: {
      type: String,
      default: 'icon/male.png'
    }
  },
  data() {
    return {
      imgSrc: '',
      loadError: false
    };
  },
  computed: {
    // 容器样式
    containerStyle() {
      const size = this.getNumberValue(this.size);
      const borderWidth = this.getNumberValue(this.borderWidth);
      
      return {
        width: `${size}rpx`,
        height: `${size}rpx`,
        borderRadius: this.shape === 'circle' ? '50%' : '4rpx',
        borderWidth: `${borderWidth}rpx`,
        borderColor: this.borderColor,
        borderStyle: borderWidth > 0 ? 'solid' : 'none'
      };
    },
    // 图片样式
    imgStyle() {
      return {
        borderRadius: this.shape === 'circle' ? '50%' : '4rpx',
      };
    }
  },
  watch: {
    src: {
      immediate: true,
      handler(newVal) {
        this.updateImageSrc(newVal);
      }
    }
  },
  methods: {
    // 将字符串或数字转为数字
    getNumberValue(val) {
      return typeof val === 'string' ? parseInt(val) : val;
    },
    // 更新图片源
    updateImageSrc(src) {
      this.loadError = false;
      
      if (!src || src === '') {
        this.imgSrc = this.defaultSrc;
        return;
      }
      
      // 检查是否为完整URL
      if (/^https?:\/\//.test(src)) {
        this.imgSrc = src;
      } else {
        // 否则视为MD5，使用helper获取URL
        this.imgSrc = helper.getImageUrl(src);
      }
    },
    // 处理图片加载错误
    handleError() {
      this.loadError = true;
      this.imgSrc = this.defaultSrc;
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar-container {
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  
  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style> 